package per.hx.bs.config.session;

import org.apache.shiro.session.SessionListener;
import org.apache.shiro.session.mgt.eis.SessionDAO;
import org.apache.shiro.web.session.mgt.DefaultWebSessionManager;

import org.crazycake.shiro.RedisManager;
import org.crazycake.shiro.RedisSessionDAO;
import org.springframework.beans.factory.annotation.Qualifier;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.session.data.redis.config.annotation.web.http.EnableRedisHttpSession;

import java.util.ArrayList;
import java.util.Collection;

/**
 * @author HuXing
 * @date 2018/3/9  15:30
 * maxInactiveIntervalInSeconds: 设置Session失效时间，使用Redis Session之后，原Boot的server.session.timeout属性不再生效
 */
@Configuration
@EnableRedisHttpSession(maxInactiveIntervalInSeconds = 86400 * 30)
public class SessionConfig {


    @Bean
    public DefaultWebSessionManager sessionManager(@Qualifier("redisManager") RedisManager redisManager) {
        DefaultWebSessionManager sessionManager = new DefaultWebSessionManager();

        int sessionTimeout = 86400 * 30;
        sessionManager.setGlobalSessionTimeout(sessionTimeout);
        sessionManager.setSessionDAO(sessionDAO(redisManager));
        sessionManager.setSessionIdUrlRewritingEnabled(false);

        Collection<SessionListener> listeners = new ArrayList<SessionListener>();

        listeners.add(new BsSessionListener());
        sessionManager.setSessionListeners(listeners);
        return sessionManager;
    }

    @Bean
    public RedisSessionDAO redisSessionDAO(@Qualifier("redisManager") RedisManager redisManager) {
        RedisSessionDAO redisSessionDAO = new RedisSessionDAO();
        redisSessionDAO.setRedisManager(redisManager);
        return redisSessionDAO;
    }

    @Bean
    public SessionDAO sessionDAO(@Qualifier("redisManager") RedisManager redisManager) {
        return redisSessionDAO(redisManager);
    }


}
